package com.security.manage.search.controller;

import com.security.manage.search.model.ComputerInfo;
import com.security.manage.search.model.ResData;
import com.security.manage.search.repository.ComputerInfoRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class ComputerInfoController {

    @Resource
    private ComputerInfoRepository computerInfoRepository;

    @PostMapping("/computer")
    public ResData addComputer(@RequestBody ComputerInfo computerInfo){
        if (computerInfo.getId()==null){
            return new ResData(0,"ID 为空，不能操作");
        }
        computerInfoRepository.save(computerInfo);
        return new ResData(1,"操作成功");
    }

    @GetMapping("/computer/{id}")
    public ResData getComputer(@PathVariable("id") Long id){
        Optional<ComputerInfo> computerInfo = computerInfoRepository.findById(id);
        return computerInfo.map(dept -> new ResData<>(1, "获取成功", dept)).orElseGet(() -> new ResData(0, "获取失败"));
    }

    @DeleteMapping("/computer/{id}")
    public ResData delComputer(@PathVariable("id") Long id){
        computerInfoRepository.deleteById(id);
        return new ResData(1,"操作成功");
    }

    @GetMapping("/computer/list")
    public ResData listRole(@RequestParam(value = "page",defaultValue = "0") Integer page,
                            @RequestParam(value = "size",defaultValue = "10") Integer size){


        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest of = PageRequest.of(page, size, sort);
        Page<ComputerInfo> pages = computerInfoRepository.findAll(of);

        Map<String,Object> map = new HashMap<>();
        map.put("total",pages.getTotalElements());
        List<ComputerInfo> collect = pages.get().collect(Collectors.toList());
        map.put("data",collect);

        return new ResData<>(1, "获取成功", map);
    }
}
